package spring.boot.factory.impl;

import org.apache.catalina.startup.Tomcat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import spring.boot.auto.config.ServletAutoConfigProperties;
import spring.boot.factory.WebServletFactory;

/**
 * @ClassName TomcatWebServletFactory
 * @Description TODO
 * @Author Toolck Rin
 * @Date 2021/3/10 23:00
 * @Version 1.0
 **/

public class TomcatWebServletFactory implements WebServletFactory {

    private ServletAutoConfigProperties servletAutoConfigProperties;

    public TomcatWebServletFactory(ServletAutoConfigProperties servletAutoConfigProperties) {
        this.servletAutoConfigProperties = servletAutoConfigProperties;
    }

    public TomcatWebServletFactory() {

    }

    @Override
    public void createServer() {
        creatAndStartTomcat();
    }

    private void creatAndStartTomcat() {
        try {
            Tomcat tomcat = new Tomcat();
            tomcat.setPort(servletAutoConfigProperties.getPort());
            String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            tomcat.addWebapp("/", path);
            tomcat.start();
            //因为  tomcat.start();是非阻塞型的，所以要阻塞一下，不能让服务停止。
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
